package com.mishitech.curso.web.security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.mishitech.curso.core.SecurityService;
import com.mishitech.curso.exception.PrimisStrutsException;
import com.mishitech.curso.objectDomain.UserVO;

public class SecurityAction extends DispatchAction {

	private final String EMPTY_VALUE = "";

	private SecurityService securityService;



	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.actions.DispatchAction#dispatchMethod(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.String)
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			HttpSession session = request.getSession();
			LoginForm loginForm = (LoginForm) form;
			UserVO userVO = new UserVO();
			userVO.setCdUser(loginForm.getCdUser());
			userVO.setPwPassword(loginForm.getPwPassword());


			// TODO Mover implementaci�n de validacion a componente ActionForm
			ActionMessages messages = validate(loginForm);
			if (!messages.isEmpty()) {
				saveMessages(request, messages);
				return mapping.findForward("fail");
			}
			
			
			UserVO user = securityService.login(loginForm);
			session.setAttribute("usuarioObj", user);			
			return mapping.findForward("success");
			
		} catch (PrimisStrutsException e) {
			throw new PrimisStrutsException(e.getMessage());
		}
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.getSession(false).invalidate();
		return mapping.findForward("index");
	}

	private ActionMessages validate(LoginForm loginForm) {
		ActionMessages messages = new ActionMessages();
		if (loginForm.getCdUser().equals(EMPTY_VALUE)
				|| loginForm.getPwPassword().equals(EMPTY_VALUE)) {
			ActionMessage msg = new ActionMessage(
					"primis.web.sec.login.campoRequerido");
			messages.add("message", msg);
		}

		return messages;
	}

	public SecurityService getSecurityService() {
		return securityService;
	}

	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}
}
